package com.jhh.pay.center.service.impl;

import com.jhh.pay.center.cfg.caching.Cache;
import com.jhh.pay.center.dao.PayChannelCfgMapper;
import com.jhh.pay.center.model.PayChannel;
import com.jhh.pay.center.model.PayChannelCfg;
import com.jhh.pay.center.model.PayChannelCfgValuePair;
import com.jhh.pay.center.service.PayChannelCfgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/5
 */
@Service
@Slf4j
public class PayChannelCfgServiceImpl implements PayChannelCfgService {
    @Autowired
    private PayChannelCfgMapper cfgMapper;

    @Autowired
    private Cache cache;

    private String cacheKey(int channelId, String version) {
        return String.format("jhh:pay:pay_channel_cfg:%d_%s", channelId, version);
    }

    private String cacheKeyByChannelId(int channelId) {
        return String.format("jhh:pay:pay_channel_cfgs:%d", channelId);
    }

    @Override
    public boolean save(PayChannelCfg cfg) {
        PayChannelCfg pcc = get(cfg.getChannelId(), cfg.getVersion());
        if (null != pcc) {
            return false;
        }
        boolean ok = cfgMapper.insert(cfg) > 0;
        if (ok) {
            cache.set(cacheKey(cfg.getChannelId(), cfg.getVersion()), cfg, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
            cache.del(cacheKeyByChannelId(cfg.getChannelId()));
        }
        return ok;
    }

    @Override
    public boolean update(PayChannelCfg cfg) {
        boolean ok = cfgMapper.update(cfg) > 0;
        if (ok) {
            cache.set(cacheKey(cfg.getChannelId(), cfg.getVersion()), cfg, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
        }
        return ok;
    }

    @Override
    public PayChannelCfg get(int channelId, String version) {
        PayChannelCfg pcc = cache.get(cacheKey(channelId, version), PayChannelCfg.class);
        if (null == pcc) {
            pcc = cfgMapper.get(channelId, version);
            if (null != pcc) {
                cache.set(cacheKey(channelId, version), pcc, TimeUnit.SECONDS.convert(3, TimeUnit.DAYS));
            }
        }
        return pcc;
    }

    @Override
    public Collection<PayChannelCfg> gets(int channelId) {
        Collection<PayChannelCfgValuePair> vals = cache.getList(cacheKeyByChannelId(channelId), PayChannelCfgValuePair.class);
        List<PayChannelCfg> acs = new ArrayList<>();
        if (vals.size() == 0) {
            vals = cfgMapper.gets(channelId);
            cache.set(cacheKeyByChannelId(channelId), vals, TimeUnit.SECONDS.convert(5, TimeUnit.DAYS));
        }
        for (PayChannelCfgValuePair vp : vals) {
            PayChannelCfg pcc = get(vp.getVal1(), vp.getVal2());
            acs.add(pcc);
        }
        return acs;
    }
}
